package com.huiyi.quickproj.jundui;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AsyncReadWriteFile {
    public static void main(String[] args) {
        // 读取的文件路径
        String inputFile = "D:\\project\\ieducation_training\\外部项目\\jundui_csv2sql\\data\\china\\population_data.csv";

        // 写入的文件路径
        String outputFile = "D:\\project\\ieducation_training\\外部项目\\jundui_csv2sql\\data\\china\\population_data.sql";

        try {
            // 读取文件内容
            List<String> lines = Files.readAllLines(Paths.get(inputFile));

            // 处理每一行
            StringBuilder processedContent = new StringBuilder();
            for (String line : lines) {
                // 在这里可以对每一行进行处理，这里示例为将每一行转换为大写
                processedContent.append(line.toUpperCase()).append("\n");
            }

            // 异步写入新文件
            writeAsync(outputFile, processedContent.toString());

            System.out.println("Async file write operation initiated.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeAsync(String filePath, String content) {
        try {
            // 将字符串转换为字节数组
            byte[] data = content.getBytes(StandardCharsets.UTF_8);

            // 打开一个异步文件通道
            AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(
                    Paths.get(filePath),
                    StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING
            );

            // 创建一个ByteBuffer，将数据写入其中
            ByteBuffer buffer = ByteBuffer.wrap(data);

            // 异步写入文件
            Future<Integer> operation = fileChannel.write(buffer, 0);

            // 等待写入操作完成
            operation.get();

            System.out.println("File written asynchronously successfully!");
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
